package com.kk.base.interceptor.admin;

import com.alibaba.fastjson.JSON;
import com.kk.base.bean.CodeMsg;
import com.kk.base.entity.admin.Menu;
import com.kk.base.entity.admin.User;
import com.kk.base.util.MenuUtil;
import com.kk.base.util.SessionUtil;
import com.kk.base.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 权限统一管理拦截器
 *
 * @author Administrator
 */
@Component
public class AdminAuthorityInterceptor implements HandlerInterceptor {

    private final Logger log = LoggerFactory.getLogger(AdminAuthorityInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        log.info("AdminAuthorityInterceptor拦截到的请求={}",request.getRequestURL());
        User loginedUser = SessionUtil.getLoginedUser();
        log.info("进入权限控制拦截器" + requestURI);
        assert loginedUser != null;
        List<Menu> authorities = loginedUser.getRole().getAuthorities();
        // 判断当前用户所属角色的请求的地址是否在允许请求的地址列表里
        if (!MenuUtil.isExistUrl(requestURI, authorities)) {
            log.info("当前用户请求的地址不在用户权限范围内" + requestURI);
            // 进入这里，表示权限不存在，首先判断是否是ajax请求
            if (StringUtil.isAjax(request)) {
                log.info("当前请求是非法的阿贾克斯请求，返回json字符串响应");
                // 表示是ajax请求,返回json数据
                try {
                    log.info("该请求无权限，已ajax方式返回提示，url={}", requestURI);
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(JSON.toJSONString(CodeMsg.ADMIN_NO_RIGHT));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return false;
            }
            //说明是普通的请求，可直接重定向到无权限提示页面
            try {
                log.info("当前请求是非法的普通请求，返回提示页面");
                log.info("该请求无权限，重定向到无权限提示页面，url={}", requestURI);
                response.sendRedirect("/system/no_right");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return false;
        }
        log.info("该请求符合权限要求，放行" + requestURI);
        return true;
    }
}
